package com.linux.huhx.codetools.transutil;

import org.junit.Assert;
import org.junit.Test;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by huhx on 2017-06-14.
 */
public class CodeRegrexUtils {

    // ${name} from map
    public static String baseReplaceFromMap(String string, Map<String, String> map, String replace) {
        Set<String> set = map.keySet();
        for (String str : set) {
            string = string.replace("${" + str + "}", map.get(str)); // 这里不能用replaceAll
        }
        return string;
    }

    // {name} from map
    public static String simpleReplaceFromMap(String string, Map<String, String> map, String replace) {
        Set<String> set = map.keySet();
        for (String str : set) {
            string = string.replace("{" + str + "}", map.get(str)); // 这里不能用replaceAll
        }
        return string;
    }

    // {0} from arrays
    public String baseReplaceFromArray(String string, List<String> list) {
//        MessageFormat.format("", new Object[]{});
//        List<Object> objects = new ArrayList<>();
//        MessageFormat.format("", objects);
        return MessageFormat.format(string, transListInfoArrays(list)); // huhx love liuling
//        return MessageFormat.format(string, list); // [huhx, liuling] love {1}
    }

    private String[] transListInfoArrays(List<String> list) {
        int length = list.size();
        String[] arrays = new String[length];
        for (int i = 0; i < length; i++) {
            arrays[i] = list.get(i);
        }
        return arrays;
    }

    @Test
    public void baseReplaceFromArray_test() {
        List<String> list = new ArrayList<>();
        list.add("huhx");
        list.add("L。");
//        Assert.assertEquals("huhx love liuling", baseReplaceFromArray("{0} love {1}", list));
        System.out.println(baseReplaceFromArray("{0} love {1}", list)); // huhx love L。
    }
}
